import { ref } from 'vue';
import api from 'axios';
import { menuItem, CRouteItem } from 'stores/model';
import { useRouter } from 'vue-router';
import { sysBaseVOAPI } from 'src/util/SysBaseConst';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';

export function getSysMenuTree () {
  //路由表
  const router = useRouter();

  //消息通知hook
  const {
    showMessage
  } = useMessageNotify();

  //存储数据数组
  let menuRoutes = ref<CRouteItem[]>([]);

  //生成菜单树并存储
  const generateMenuTree = (list: menuItem[]): CRouteItem[] => {
    let routeList: CRouteItem[] = [];

    //递归函数
    const filterTree = (ls: menuItem[], arr: CRouteItem[]) => {
      ls.forEach((item: menuItem) => {
        let el = [] as CRouteItem[];
        if (item.children && item.children.length > 0) {
          filterTree(item.children, el);
        }

        //路由节点
        arr.push({
          name: item.value,
          path: item.url,
          meta: {
            icon: item.icon,
            title: item.label
          },
          component: () => import(`../pages/${item.component}`),
          children: el
        });
      });
    };

    //调用递归函数
    filterTree(list, routeList);

    return routeList;
  }

  //路由封装
  const routerPackage = (routes: CRouteItem[]) => {
    if ((routes) && (routes.length > 0)) {
      routes.filter((item: CRouteItem) => {
        if (item.name !== 'Layout') {
          if (router.hasRoute(item.name)) {
            router.removeRoute(item.name);
          }

          //加入到home菜单下
          router.addRoute('Layout', item);
        }

        //递归
        if (item.children && item.children.length > 0) {
          routerPackage(item.children);
        }

        return true;
      })
    }
  }

  //读取菜单树
  const getMenuTreeVO = (range: number) => {
    api.post(sysBaseVOAPI.MENU_VO_TREE, {
      privilege: range
    }).then((res: any) => {
      if (res.data.message === 'Success') {
        let arr: menuItem[] = [];

        //取出数据
        arr = res.data.data;
        //console.log(arr);

        //存储到menuRoutes
        menuRoutes.value = generateMenuTree(arr);

        //加入路由表
        routerPackage(menuRoutes.value);
      } else {
        showMessage(res.data.message);
      }
    }).catch((error: any) => {
      showMessage(error.message);
    });
  }


  return {
    menuRoutes,
    getMenuTreeVO
  }
}
